package com.mali.mq.template;

import com.mali.mq.domain.po.BizLog;
import com.mali.mq.producer.LogProducer;
import lombok.RequiredArgsConstructor;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

/**
 * 统一业务日志模板工具类
 */
@Component
@RequiredArgsConstructor
public class LogTemplate {

    private final LogProducer logProducer;

    /**
     * 发送成功日志
     */
    public void sendSuccessLog(String service, String module, String action,
                               Long operatorId, Long targetId, String message) {
        BizLog log = buildLog(service, module, action, operatorId, targetId, "SUCCESS", message);
        send(log);
    }

    /**
     * 发送失败日志
     */
    public void sendFailLog(String service, String module, String action,
                            Long operatorId, Long targetId, String reason) {
        BizLog log = buildLog(service, module, action, operatorId, targetId, "FAIL", reason);
        send(log);
    }

    /**
     * 构造业务日志
     */
    private BizLog buildLog(String service, String module, String action,
                            Long operatorId, Long targetId, String result, String message) {
        return BizLog.builder()
                .traceId(getTraceId())
                .service(service)
                .module(module)
                .action(action)
                .operatorId(operatorId)
                .targetId(targetId)
                .result(result)
                .message(message)
                .timestamp(System.currentTimeMillis())
                .build();
    }

    /**
     * 获取链路追踪 ID（支持 Sleuth、Skywalking）
     */
    private String getTraceId() {
        String traceId = MDC.get("traceId"); // Sleuth: "X-B3-TraceId"
        return traceId != null ? traceId : "UNKNOWN";
    }

    /**
     * 日志统一发送逻辑
     */
    private void send(BizLog log) {
        logProducer.sendLog(log);
    }
}
